﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SuperQuiz.Logic;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.Data.Xml.Dom;

namespace SuperQuiz.QualityChecklist
{
    public class QualityChecklistQuizPlay : QuizPlay
    {
        protected override void ShareResults(DataPackage requestData)
        {
            var resourceLoader = new ResourceLoader();
            requestData.Properties.Title = String.Format("{0} - {1}", Quiz.Category.Name, Quiz.Name);

            var xml = new XmlDocument();
            var body = xml.CreateElement("DIV");
            xml.AppendChild(body);

            var quizName = xml.CreateElement("H1");
            quizName.InnerText = Quiz.Name;
            body.AppendChild(quizName);

            var questionName = xml.CreateElement("H2");
            questionName.InnerText = "Resultado";
            body.AppendChild(questionName);

            var quizAnswers = xml.CreateElement("TABLE");
            body.AppendChild(quizAnswers);

            var ultimoTitulo = "";
            foreach (var answer in Results.Items)
            {
                if (!ultimoTitulo.Equals(answer.Question.Title))
                {
                    ultimoTitulo = answer.Question.Title;
                    var trTitulo = xml.CreateElement("TR");
                    quizAnswers.AppendChild(trTitulo);

                    var tdTitulo = xml.CreateElement("TD");
                    tdTitulo.SetAttribute("colspan", "2");
                    trTitulo.AppendChild(tdTitulo);

                    var h3Titulo = xml.CreateElement("H3");
                    h3Titulo.InnerText = answer.Question.Title;
                    tdTitulo.AppendChild(h3Titulo);
                }
                
                var quizAnswer = xml.CreateElement("TR");
                quizAnswers.AppendChild(quizAnswer);                

                var quizAnswerName = xml.CreateElement("TD");
                quizAnswerName.InnerText = answer.Question.SubTitle;
                quizAnswer.AppendChild(quizAnswerName);

                var quizAnswerDescription = xml.CreateElement("TD");
                if (answer.SelectedAnswer != null)
                {
                    quizAnswerDescription.InnerText = answer.SelectedAnswer.Name;
                }
                else
                {
                    quizAnswerDescription.InnerText = "-";
                }
                quizAnswer.AppendChild(quizAnswerDescription);
            }
            requestData.SetHtmlFormat(HtmlFormatHelper.CreateHtmlFormat(xml.GetXml()));
        }
    }
}
